import datetime
import re


COMPLETED = 'x'  # used to mark complete status in strings

class Task(object):
    """ This is where we create the tasks or read them in """
    def __init__(self, taskString = None):
        self._completed = False
        self.dtCompleted = None
        self.priority = None
        self.dtCreated = datetime.date.today()
        self.text = ''
        self.projects = list()
        self.contexts = list()
        if taskString:
            self.dtCreated = None
            self.fromString(taskString)

    @property
    def completed(self):
        return self._completed

    @completed.setter
    def completed(self, value):
        if value is True:
            self._completed = True
            self.dtCompleted = datetime.date.today()
        elif value is False:
            self._completed = False
            self.dtCompleted = None
        else:
            raise ValueError("Completed value must be true or false, not %s" % value)

    def fromString(self, s):
        """parse task from string (s) and populate instance vars"""
        splitTask = s.split()
        print splitTask
#       check for completion 'x' and date, if true update vars and remove items
        if splitTask[0] is COMPLETED and re.findall('\d{4}-\d\d-\d\d', splitTask[1]):
            if isValidDate(splitTask[1]):
                self.completed = True
                self.dtCompleted = isValidDate(splitTask[1])
            else:
                self.completed = False
#                self.dtCompleted = None  # not needed as setter takes care if it
            splitTask = splitTask[2:]
#       check for priority
        if splitTask[0].startswith( '(' ) and splitTask[0].endswith( ')'):
            self.priority = splitTask[0].translate(None, '()')
            splitTask = splitTask[1:]
#       check for creation date
        if isValidDate(splitTask[0]):
            self.dtCreated = isValidDate(splitTask[0])
            splitTask = splitTask[1:]
        else:
            pass # ignore, this isn't a date
#        try:
#            self.dtCreated = datetime.datetime.strptime(splitTask[0], '%Y-%m-%d').date()
#            splitTask = splitTask[1:]
#        except ValueError:
#            pass # ignore, this isn't a date
#       after ruling out the special cases - this is what all tasks could have
        self.text = ' '.join(splitTask)
        for item in splitTask:
            if item.startswith( '@'):
                self.contexts.append(item)
            elif item.startswith( '+'):
                self.projects.append(item)

    def toString(self):
        """format object in todo.txt format and return string"""
        taskString = ''
        if self.completed is True:
            taskString += "%s %s " % (COMPLETED, convertDateToString(self.dtCompleted))
#            taskString += 'x ' + datetime.datetime.strftime(self.dtCompleted, '%Y-%m-%d' ) + ' '
        if self.priority:
            taskString += '(%s) ' % self.priority
        if self.dtCreated is True:
            taskString += '%s ' % convertDateToString(self.dtCreated)
#            taskString += datetime.datetime.strftime(self.dtCreated, '%Y-%m-%d' ) + ' '
        taskString += self.text
        return taskString

def isValidDate(date_value):
    """ check if date is valid, return date if true, False if not """
    try:
        return datetime.datetime.strptime(date_value, '%Y-%m-%d').date()
    except ValueError:
        return False

def convertDateToString(date_value):
    """ receive date, convert to string, and return """
    return datetime.datetime.strftime(date_value, '%Y-%m-%d' )